#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
账号管理控制器
整合路由和控制器功能
"""

from flask import Blueprint, request
from dao.account_dao import AccountDAO
from utils.R import R
from settings import get_logger

# API版本
API_VERSION = 'v1'

# 创建蓝图，设置URL前缀
account_bp = Blueprint('account', __name__, url_prefix=f'/api/{API_VERSION}/account')

class AccountController:
    """
    账号管理控制器
    整合路由和控制器功能
    """
    
    def __init__(self):
        self.logger = get_logger(__name__)
        self.account_dao = AccountDAO()
        self._register_routes()
    
    def _register_routes(self):
        """
        注册所有路由
        """
        # 注册路由装饰器，路由前缀已在蓝图中设置，这里只需要指定具体路径
        account_bp.route('/', methods=['GET'])(self.get_accounts)
        account_bp.route('/', methods=['POST'])(self.create_account)
        account_bp.route('/<account_id>', methods=['PUT'])(self.update_account)
        account_bp.route('/<account_id>', methods=['DELETE'])(self.delete_account)
        account_bp.route('/<account_id>', methods=['GET'])(self.get_account)
    
    def get_accounts(self):
        """
        获取账号列表
        
        Returns:
            ApiResponse: 响应数据
        """
        try:
            accounts = self.account_dao.get_all_accounts()
            self.logger.info(f"获取账号列表成功，共 {len(accounts)} 个账号")
            self.logger.debug(f"账号列表: {accounts}")
            
            data = {
                "accounts": [account.to_dict() for account in accounts],
                "total": len(accounts)
            }
            
            return R.ok(data=data, message="获取账号列表成功")
            
        except Exception as e:
            self.logger.error(f"获取账号列表失败: {e}")
            return R.fail(message="获取账号列表失败")
    
    def create_account(self):
        """
        创建账号
        
        Returns:
            ApiResponse: 响应数据
        """
        try:
            data = request.get_json()
            if not data:
                return R.fail(message="请求数据为空", code=400)
                
            # 验证必填字段
            if not data.get('account'):
                return R.validation_error(message="账号不能为空")
            
            if not data.get('alias'):
                return R.validation_error(message="别名不能为空")
            
            # 检查账号是否已存在
            existing_account = self.account_dao.get_account_by_name(data['account'])
            if existing_account:
                return R.validation_error(message="账号已存在")
            
            # 创建账号
            self.logger.info(f"创建账号参数: {data}")
            account = self.account_dao.create_account(data)
            self.logger.info(f"创建账号成功，账号ID: {account.id}")
            return R.ok(data=account.to_dict(), message="创建账号成功")
            
        except Exception as e:
            self.logger.error(f"创建账号失败: {e}")
            return R.fail(message="创建账号失败")
    
    def update_account(self, account_id):
        """
        更新账号
        
        Args:
            account_id (str): 账号ID
            
        Returns:
            ApiResponse: 响应数据
        """
        try:
            data = request.get_json()
            if not data:
                return R.fail(message="请求数据为空", code=400)
                
            # 检查账号是否存在
            account = self.account_dao.get_account_by_id(account_id)
            if not account:
                return R.not_found(message="账号不存在")
            
            # 如果更新账号名，检查是否重复
            if 'account' in data and data['account'] != account.account:
                existing_account = self.account_dao.get_account_by_name(data['account'])
                if existing_account:
                    return R.validation_error(message="账号名已存在")
            
            # 更新账号
            updated_account = self.account_dao.update_account(account_id, data)
            self.logger.info(f"更新账号成功，账号ID: {account_id}")
            return R.ok(data=updated_account.to_dict(), message="更新账号成功")
            
        except Exception as e:
            self.logger.error(f"更新账号失败: {e}")
            return R.fail(message="更新账号失败")
    
    def delete_account(self, account_id):
        """
        删除账号
        
        Args:
            account_id (str): 账号ID
            
        Returns:
            ApiResponse: 响应数据
        """
        try:
            # 检查账号是否存在
            account = self.account_dao.get_account_by_id(account_id)
            if not account:
                return R.not_found(message="账号不存在")
            
            # 删除账号
            self.account_dao.delete_account(account_id)
            self.logger.info(f"删除账号成功，账号ID: {account_id}")
            return R.ok(message="删除账号成功")
            
        except Exception as e:
            self.logger.error(f"删除账号失败: {e}")
            return R.fail(message="删除账号失败")
    
    def get_account(self, account_id):
        """
        获取账号详情
        
        Args:
            account_id (str): 账号ID
            
        Returns:
            ApiResponse: 响应数据
        """
        try:
            # 获取账号
            account = self.account_dao.get_account_by_id(account_id)
            if not account:
                return R.not_found(message="账号不存在")
            
            self.logger.info(f"获取账号详情成功，账号ID: {account_id}")
            return R.ok(data=account.to_dict(), message="获取账号详情成功")
            
        except Exception as e:
            self.logger.error(f"获取账号详情失败: {e}")
            return R.fail(message="获取账号详情失败")


# 实例化控制器，确保路由被注册
account_controller = AccountController()